package com.suny.utils;

import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.stereotype.Component;

import java.util.Random;


/***
 * SourceCode转换（中文转拼音+时间戳）
 * @author xsh
 */
@Component
@Slf4j
public class PinYinUtil {

    public static String getPinyin(String china) {
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = china.trim().toCharArray();
        StringBuffer result = new StringBuffer();
        String code = String.valueOf(System.currentTimeMillis());
        try {
            for (int i = 0; i < arrays.length; i++) {
                char ti = arrays[i];
                if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]")) { //匹配是否是中文
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, formart);
                    try {
                        if (temp.length > 0) {
                            result.append(temp[0]);
                        }
                    } catch (NullPointerException e) {
                    }
                } else {
                    result.append(ti);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

        String substring = "";
        if (result.length() >= 37){
            substring  = result.substring(0, 37);
        }else {
            substring = result.toString();
        }

        return substring + code;
    }


    public static String getId(String nameEn) {
        int i = new Random().nextInt(9999);
        String prefix= "";
        if (StringUtils.isNotEmpty(nameEn) && nameEn.length() >= 33){
            prefix  = nameEn.substring(0, 33);
        }else{
            prefix = nameEn;
        }
        String code  = String.valueOf(System.currentTimeMillis()) + i;
        String result = prefix + code;
        return result;
    }
}